package com.yueshop.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.yueshop.common.constant.ProductConstant;
import com.yueshop.common.to.SkuEsModel;
import com.yueshop.common.to.SkuHasStockVo;
import com.yueshop.common.to.SkuReductionTo;
import com.yueshop.common.to.SpuBoundTo;
import com.yueshop.common.utils.R;
import com.yueshop.product.entity.*;
import com.yueshop.product.feign.CouponFeignService;
import com.yueshop.product.feign.SearchFeignService;
import com.yueshop.product.feign.WareFeignService;
import com.yueshop.product.service.*;
import com.yueshop.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.common.utils.Query;

import com.yueshop.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;


    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    SearchFeignService searchFeignService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
    //@GlobalTransactional //使用seata at模式控制分布式事务
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.baseMapper.insert(spuInfoEntity);
        //2.保存spu描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(spuInfoEntity.getId());
        infoDescEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(infoDescEntity);
        //3.保存spu图片集  pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);
        //4.保存spu 规格参数  pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(attr.getAttrId());

            AttrEntity byId = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;

        }).collect(Collectors.toList());
        //批量保存
        productAttrValueService.saveBatch(collect);

        //5.保存spu积分信息   yueshop_sms--> sms_spu_bounds[跨库]
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r=  couponFeignService.saveSpuBounds(spuBoundTo);

        if(r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }


        //6.保存spu对应的sku信息
            //6.1 保存sku 基本信息  pms_sku_info
        List<Skus> skus = vo.getSkus();
        if(skus!=null&&skus.size()>0){
            skus.forEach(item->{

                String defaultImg= "";
                for (Images image:item.getImages()) {
                    if(image.getDefaultImg()==1){
                        defaultImg=image.getImgUrl();
                    }
                }
                /**
                 *     private String skuName;
                 *     private BigDecimal price;
                 *     private String skuTitle;
                 *     private String skuSubtitle;
                 */
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.save(skuInfoEntity);
                //获取skuid 方便进行关联
                Long skuId = skuInfoEntity.getSkuId();

                //6.2.保存sku图片信息  pms_sku_images
                List<SkuImagesEntity> SkuImagesEntites = item.getImages().stream().map(img -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuId);
                    imagesEntity.setImgUrl(img.getImgUrl());
                    imagesEntity.setDefaultImg(img.getDefaultImg());
                    return imagesEntity;
                }).filter(entity -> {
                    //不为空 返回true 保存 为空返回false 去除掉
                    return !StringUtils.isEmpty(entity.getImgUrl());
                   }).collect(Collectors.toList());
                skuImagesService.saveBatch(SkuImagesEntites);

                //6.3 保存sku的销售属性 pms_sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> collect1 = attr.stream().map(attr1 -> {
                    SkuSaleAttrValueEntity attrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr1, attrValueEntity);
                    attrValueEntity.setSkuId(skuId);
                    return attrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect1);


                //6.4 保存sku 的优惠 满减 会员价格等信息[跨库]
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if(skuReductionTo.getFullCount()>0 ||skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }

                //yueshop_sms -->  sms_sku_ladder 打折表
                // sms_sku_full_reduction 满减表  10000-50
                //sms_member_price  会员价格表 会员等级对应价格

            });
        }


    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        /**
         * status: 0
         * key: 华为
         * brandId: 21
         * catelogId: 225
         */
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        //获取关键字
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.and(w->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        //状态status  status=1 and (id=1 or spu_name like %huaweu%)
        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        //品牌id
        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId)&&!"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        //分类id

        String catelogId = (String)params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)&&!"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void up(long spuId) {


        // 查询当前sku 所有可以被检索的规格属性
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueService.baseAttrListforspu(spuId);
        //.获取 gai spuId 对应的属性id
        List<Long> attrIds =productAttrValueEntities.stream().map(productAttrValueEntityp->{
            return productAttrValueEntityp.getAttrId();
        }).collect(Collectors.toList());

         //查询pms_attr表中search_type=1 可以被检索的数据
        List<Long> searchAttrIds= attrService.selectSearchAttrIds(attrIds);

        Set<Long> idSet=new HashSet<>(searchAttrIds);

        //获取可以检索的数据
        List<SkuEsModel.Attrs> attrs = productAttrValueEntities.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attr = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attr);
            return attr;
        }).collect(Collectors.toList());



        //组装需要的数据
        //1.pms_sku_info表查询出 当前spuId对应的所有sku 信息
       List<SkuInfoEntity> skus=  skuInfoService.getSkusBySpuId(spuId);

        List<Long> ids = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());

        Map<Long,Boolean> stockMap= null;
        //发送远程调用 查询系统sku对应的库存是否有(不做精确查询)
        try{
            R r = wareFeignService.getSkusHasStock(ids);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            //查询对应的sku是否有库存  map集合中  key skuid  value值是是否有库存
            stockMap= r.getData(typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId,SkuHasStockVo::getHasStock));

        }catch (Exception e){
            log.error("库存查询服务出现异常,原因{}",e);
        }


        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skus.stream().map(sku -> {
            SkuEsModel skuEsModel = new SkuEsModel();
            //1.属性对拷
            BeanUtils.copyProperties(sku, skuEsModel);
            //单独设置不一样的属性
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

            // 设置库存信息
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            // 设置 热度评分
            skuEsModel.setHotScore(0L);
            //获取品牌信息 及分类信息
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandId(brand.getBrandId());
            skuEsModel.setBrandName(brand.getName());
            skuEsModel.setBrandImg(brand.getLogo());

            CategoryEntity category = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(category.getName());
            //设置 可以检索的属性
            skuEsModel.setAttrs(attrs);
            return skuEsModel;
        }).collect(Collectors.toList());


        //将数据发送给es进行保存
        R r = searchFeignService.productStatusUp(collect);
        if(r.getCode()==0){
            //保存成功 还需要修改当前spu的状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else{
            //TODO 远程调用失败 会会不会自动重试来调用  重试机制
            /**
             *  feign 调用流程
             *  1.构造请求数据,将对象转为json
             *  RequestTemplate template = this.buildTemplateFromArgs.create(argv);
             *  2.发送请求进行执行(执行成功会节码响应数据)
             *   return this.executeAndDecode(template);
             *  3. 执行请求会有重试机制
             *  while(true) {
             *             try {
             *                 return this.executeAndDecode(template);
             *             } catch (RetryableException var8) {
             *                 RetryableException e = var8;
             *                 try {
             *                     retryer.continueOrPropagate(e);
             *                 } catch (RetryableException var7) {
             *                 }
             */
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long id) {
        SkuInfoEntity byId = skuInfoService.getById(id);

        return getById(byId.getSpuId());
    }


}